package wechat

import (
	"errors"
	"fmt"
)

type Wechat struct {
	Config
}

type Config struct {
	AppID     string
	AppSecret string
}

func (this *Wechat) NewWechat(config *Config) {
	this.Config.AppID = config.AppID
	this.Config.AppSecret = config.AppSecret
}

func (this *Wechat) GetAccessToken() (string, error) {
	api := "https://api.weixin.qq.com/cgi-bin/token?"
	parmas := map[string]string{
		"appid":      this.AppID,
		"secret":     this.AppSecret,
		"grant_type": "client_credential",
	}
	api = api + qsStringify(parmas)
	result, err := httpGet(api)
	if err != nil {
		return "", err
	}
	if _, ok := result["access_token"]; !ok {
		err := errors.New("获取access_token出错：" + result["errmsg"].(string))
		return "", err
	}
	return result["access_token"].(string), nil
}
func (this *Wechat) SendTpl(
	accossToken string,
	openid string,
	template_id string,
	data map[string]interface{},
) (map[string]interface{}, error) {

	api := "https://api.weixin.qq.com/cgi-bin/message/template/send?"
	params := map[string]string{"access_token": accossToken}
	api = api + qsStringify(params)
	payload := map[string]interface{}{
		"touser":      openid,
		"template_id": template_id,
		"data":        data,
	}
	result, err := httpPost(api, payload)
	if err != nil {
		return payload, err
	}
	return result, nil
}

func (this *Wechat) GetUserInfo(openid string, accessToken string) {
	api := "https://api.weixin.qq.com/sns/userinfo?"
	params := map[string]string{
		"access_token": accessToken,
		"openid":       openid,
		"lang":         "zh_CN",
	}
	api = api + qsStringify(params)
	fmt.Println("api", api)
	userInfo, _ := httpGet(api)
	fmt.Println("userInfo", userInfo)
}
